<?php
/*
+--------------------------------------------------------------------------
|   IKPHP [#RELEASE_VERSION#]
|   ========================================
|   By IKPHP Software
|   © 2013 - 2050 WeCenter. All Rights Reserved
|   http://www.ikphp.com
|   ========================================
|   Author: 小麦 <ikphp@sina.cn>
+---------------------------------------------------------------------------
*/
defined ( 'IN_IKPHP' ) or exit ( 'WebSite Access Denied' );
class exceptions {
    /**
     * 自定义异常处理
     * @access public
     * @param mixed $e 异常对象
     */	
	public static function exception_error($e){
        $error = array();
        $phpmsg = array();	
        $error['message']   =   $e->getMessage();
        $trace              =   $e->getTrace();
        if('E'==$trace[0]['function']) {
            $error['file']  =   $trace[0]['file'];
            $error['line']  =   $trace[0]['line'];
        }else{
            $error['file']  =   $e->getFile();
            $error['line']  =   $e->getLine();
        }
        krsort($trace);
		$trace[] = array('file'=>$e->getFile(), 'line'=>$e->getLine(), 'function'=> 'break');
		$phpmsg = array();		
		foreach ($trace as $ev) {
			if(!empty($ev['function'])) {

				$fun = '';
				if(!empty($ev['class'])) {
					$fun .= $ev['class'].$ev['type'];
				}
				$fun .= $ev['function'].'(';
				if(!empty($ev['args'])) {
					$mark = '';
					foreach($ev['args'] as $arg) {
						$fun .= $mark;
						if(is_array($arg)) {
							$fun .= 'Array';
						} elseif(is_bool($arg)) {
							$fun .= $arg ? 'true' : 'false';
						} elseif(is_int($arg)) {
							$fun .= (defined('APP_DEBUG') && APP_DEBUG) ? $arg : '%d';
						} elseif(is_float($arg)) {
							$fun .= (defined('APP_DEBUG') && APP_DEBUG) ? $arg : '%f';
						}
						$mark = ', ';
					}
				}

				$fun .= ')';
				$ev['function'] = $fun;
			}
			$phpmsg[] = array(
			    'file' => str_replace(array(SITE_PATH, '\\'), array('', '/'), $ev['file']),
			    'line' => $ev['line'],
			    'function' => $ev['function'],
			);			
		}        
        $error['trace']     =   $phpmsg; 
        //log::record($error['message'],Log::ERR);
        // 发送404信息
        header('HTTP/1.1 404 Not Found');
        header('Status:404 Not Found');
        self::show_error($error);	
	}
    /**
     * IKPHP系统自定义错误
     * @access public
     * @param int $errno 错误类型
     * @param string $errstr 错误信息
     * @param string $errfile 错误文件
     * @param int $errline 错误行数
     * @return void
     */		
	public static function system_error($errno, $errstr, $errfile, $errline){
		switch ($errno) {
          case E_ERROR:
          case E_PARSE:
          case E_CORE_ERROR:
          case E_COMPILE_ERROR:
          case E_USER_ERROR:
            ob_end_clean();
            $errorStr = "$errstr ".$errfile." 第 $errline 行.";
            //if(C('LOG_RECORD')) log::write("[$errno] ".$errorStr,Log::ERR);
            self::show_error($errorStr);
            break;
          default:
            $errorStr = "[$errno] $errstr ".$errfile." 第 $errline 行.";
            IKPHP::trace($errorStr,'','NOTIC');
            break;
      	}		
	}
    /**
     * 致命性错误
     * @return void
     */	
	public static function shutdown_error(){
	    //log::save();
        if ($e = error_get_last()) {
            switch($e['type']){
              case E_ERROR:
              case E_PARSE:
              case E_CORE_ERROR:
              case E_COMPILE_ERROR:
              case E_USER_ERROR:  
                ob_end_clean();
                self::show_error($e);
                break;
            }
        }	
	}	
    /**
     * 错误输出
     * @param mixed $error 错误
     * @return void
     */	
	public static function show_error( $error ){
        $e = array();
        if (APP_DEBUG || IS_CLI) {  
            //调试模式下输出错误信息
            if (!is_array($error)) {
                $trace          = debug_backtrace();
                $e['message']   = $error;
                $e['file']      = $trace[0]['file'];
                $e['line']      = $trace[0]['line'];
                ob_start();
                debug_print_backtrace();
                $e['trace']     = ob_get_clean();
            } else {
                $e              = $error;
            }
            if(IS_CLI){
                exit(iconv('UTF-8','gbk',$e['message']).PHP_EOL.'FILE: '.$e['file'].'('.$e['line'].')'.PHP_EOL.$e['trace']);
            }
        } else {
            //否则定向到错误页面
            $error_page         = C('ERROR_PAGE');
            if (!empty($error_page)) {
                redirect($error_page);
            } else {
                $message        = is_array($error) ? $error['message'] : $error;
                $e['message']   = C('SHOW_ERROR_MSG')? $message : C('ERROR_MESSAGE');
            }
        }
        // 包含异常页面模板
        $exceptionFile =  C('TMPL_EXCEPTION_FILE',null,IKPHP_PATH.'tmpl/ik_exception.tpl');
        include $exceptionFile;
        exit;
	}
}